import React from 'react';
import { useList } from './useList';
import { Table, message as antdMessage, Modal, Form, Input, Button } from 'antd'
import { columns } from './columns'
import axios from 'axios';
import { useModal } from './model';



const Index: React.FC = () => {
  const { list, getList, setSearchValue } = useList()
  const { open, closeModal, openModal, title } = useModal("编辑");

  const handleDelete = async (row) => {
    await axios.delete(`/xx/list/${row.id}`);
    await getList();
    antdMessage.success('删除ok')

  }
  const handleEdit = (row) => {
    openModal();
    form.setFieldsValue(row);
  }
  const handleAdd = () => {
    openModal();
    form.resetFields()
  }
  const handleOk = async () => {
    const data = form.getFieldsValue()
    if(data.id) {
      // 编辑
      await axios.put('/xx/list/' + data.id, data)
    } else  {
      // 添加
      await axios.post('/xx/list', data)
    }
    closeModal();
    getList();
    antdMessage.success('操作成功')
  }   
  const onSearch = (value) => {
    setSearchValue(value.trim())
  }
  const [form] = Form.useForm();

  return (
    <div>
      <Input.Search onSearch={(value) => onSearch(value)}></Input.Search>
      <Button type="primary" onClick={() => handleAdd()}>添加</Button>
      <Table dataSource={list} columns={columns({ handleDelete, handleEdit })}></Table>
      <Modal
        title={title}
        open={open}
        onCancel={closeModal}
        onOk={() => handleOk()}
        cancelText="取消"
        okText="确定"
      >
        <Form form={form} labelCol={{ span: 4 }}>
          <Form.Item label="id" name="id">
            <Input placeholder='请输入id' disabled></Input>
          </Form.Item>
          <Form.Item label="title" name="title">
            <Input placeholder='请输入title'></Input>
          </Form.Item>
          <Form.Item label="word" name="word">
            <Input placeholder='请输入word'></Input>
          </Form.Item>
          <Form.Item label="image" name="image">
            <Input placeholder='请输入image'></Input>
          </Form.Item>
          <Form.Item label="price" name="price">
            <Input placeholder='请输入price'></Input>
          </Form.Item>
          <Form.Item label="datetime" name="datetime">
            <Input placeholder='请输入datetime'></Input>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Index